const workRecords = require("../models/workRecords")
const point = require("../models/point")
const question = require("../models/question")
const homework = require("../models/homework")
const fs = require('fs')
const xlsx = require('xlsx')

var express = require('express');
var router = express.Router();
//  知识点标题  题目信息  应作人数  答对人数 正确率  题型
const formidable = require('formidable');

router.post('/', (req, res, next) => {
  var form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    if (err) {
        res.json({ 'state': false })
    } else {
      homework.find({
        seq: fields.seq
      },{
        stu_num: 1,
        question: 1
      }, async(err, stu) => {
        if (err) {
          res.json({ 'state': false, 'msg': err });
        } else{

          // var is_exist = () => {
          //   return new Promise(function (resolve, reject) {
          //     let flag = false;
          //     let file_path = './workAnalysis/'+ fields.seq + '_TotalAnalysis.xlsx';
          //     fs.exists(file_path, exists => {
          //       // console.log(exists);
          //       if(exists) {
          //         flag = true;
          //         resolve(flag);
          //       }else {
          //         resolve(flag);
          //       }
          //     })
          //   })
          // }
          console.log(stu)

          async function find_ques() {
            let message = [];
            for(let i=0; i<stu[0].question.length; i++) {
              let point_message = await point.find({
                _id: stu[0].question[i].pointId
              })
              message[i] = {}
              message[i].pointTitle = point_message[0].title
              if(stu[0].question[i].questionId !== "") {
                //提高题
                let ques_message = await question.find({
                  _id: stu[0].question[i].questionId
                })
                message[i].ques = ques_message[0]
              } else {
                //基础题
                message[i].ques = point_message[0].practice
                //统一两边key
                message[i].ques.question = point_message[0].practice.question_editor_Content
              }
              message[i].pointId = stu[0].question[i].pointId
              message[i].questionId = stu[0].question[i].questionId
            }
            return message
          }

          var find_num = () => {
            return new Promise(function (resolve, reject) {
              workRecords.find({
                seq: fields.seq
              }, (err, docs) => {
                if(err) {
                  res.json({ 'state': false, 'msg': err });
                } else {
                  let submit_num = docs.length;
                  if(submit_num===0){
                    res.json({ 'state': false, 'msg': '还没有学生提交作业' });
                  }
                  let result = []
                  docs.forEach(ele => {
                    result.push(ele.question_answer)
                  })
                  resolve(result)
                }
              })
            })
          }
          // let flag = await is_exist()
          let ans_num = await find_num()
          let ques_mes = await find_ques()
          let result_data = []
          let xlsx_data = []
          for(let i=0; i<ques_mes.length; i++){
            result_data[i] = {}
            xlsx_data[i] = {}
            result_data[i].message = ques_mes[i]
            result_data[i].ques = ques_mes[i].ques.question
            result_data[i].pointTltle = ques_mes[i].pointTitle
            xlsx_data[i]['题目标题'] = ques_mes[i].pointTitle
            result_data[i].right = 0
            result_data[i].percent = ''
            result_data[i].stuNum = stu[0].stu_num
            if(ques_mes[i].ques.type==="xuanze"){
              result_data[i].type = "选择"
              let list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
              ques_mes[i].ques.items.forEach((ele,k) => {
                result_data[i].ques = `${result_data[i].ques}<div>${list[k]} ${ele}</div>` 
              })
            } else if(ques_mes[i].ques.type==="panduan"){
              result_data[i].type = "判断"
            } else if(ques_mes[i].ques.type==="jianda"){
              result_data[i].type = "简答"
            }
            xlsx_data[i]['题目类型'] = result_data[i].type
            xlsx_data[i].stu_num = stu[0].stu_num
            xlsx_data[i].right = 0
            xlsx_data[i].percent = ''
            
          }
          ans_num.forEach(ele => {
            ele.forEach(e => {
              if(e.result===true){
                let index = result_data.findIndex((item) => {
                  return (item.message.pointId===e.pointId && item.message.questionId===e.questionId)
                })
                result_data[index].right++
                xlsx_data[index].right++
              }
            })
          })
          result_data.forEach(ele => {
            // console.log(ele.right,ele.stuNum)
            ele.percent = `${parseFloat((ele.right / ans_num.length *100).toFixed(2))}%`
          })
          xlsx_data.forEach(ele => {
            // console.log(ele.right,ele.stuNum)
            ele.percent = `${parseFloat((ele.right / ans_num.length *100).toFixed(2))}%`
          })
          let buffer = xlsx.utils.json_to_sheet(xlsx_data);
          let key = Object.keys(buffer).sort();
          let ref = key[1] + ':' + key[key.length-1];
          let workbook = {
            SheetNames: ['sheetname'],
            Sheets: {
              'sheetname': Object.assign({}, buffer, {'!ref': ref})
            },
          }
          xlsx.writeFile(workbook, './workAnalysis/' + fields.seq + '_TotalAnalysis.xlsx');
          res.json({ 'state': true, 'data': result_data });
        }
      })
    }
  })
})

module.exports = router;